package com.yyaccp.hncc.dms.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.yyaccp.hncc.common.DmsConstants;
import com.yyaccp.hncc.common.vo.dms.DmsDictDataManageVO;
import com.yyaccp.hncc.common.vo.dms.DmsDiseVO;
import com.yyaccp.hncc.dms.domain.DmsDictDataManage;
import com.yyaccp.hncc.dms.domain.DmsNonDrug;
import com.yyaccp.hncc.dms.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.yyaccp.hncc.dms.domain.DmsFrequentUsed;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.*;
//com.yyaccp.hncc.common模块的包引入
import com.yyaccp.hncc.common.vo.dms.DmsFrequentUsedVO;
import com.yyaccp.hncc.common.util.BeanCopierUtil;

import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 医生常用诊断（疾病）、检查检验处置、中药西药中成药Controller
 *
 * @author ruoyi
 * @date 2020-08-20
 */
@Api(tags = "医生常用诊断（疾病）、检查检验处置、中药西药中成药")
@RestController
@RequestMapping("/dms/used")
public class DmsFrequentUsedController extends BaseController {
    @Autowired
    private IDmsFrequentUsedService dmsFrequentUsedService;

    @Autowired
    private IDmsDrugService dmsDrugService;

    @Autowired
    private IDmsNonDrugService dmsNonDrugService;

    @Autowired
    private IDmsDiseService dmsDiseService;

    @Autowired
    private IDmsDictDataManageService dmsDictDataManageService;
    /**
     * 常用项添加或删除的id
     */
    Integer id;
    /**
     * 当前所在的常用项类别
     */
    Integer type;
    /**
     *
     */
    DmsFrequentUsed dmsFrequentUsed;
    /**
     *
     */
    DmsFrequentUsed used = new DmsFrequentUsed();
    /**
     * 获得当前登录用户id
     */
    Long userId ;

    /**
     * 查询常用项数据字典列表
     */
    @PreAuthorize("@ss.hasPermi('dms:used:dictData')")
    @GetMapping("/dictDataList")
    @ApiOperation(value = "字典列表", notes = "医生常用诊断（疾病）、检查检验处置、中药西药中成药",
            code = 200, produces = "application/json", protocols = "Http",
            response = TableDataInfo.class, httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsFrequentUsedVO对象", type = "DmsFrequentUsedVO")
    public AjaxResult dmsDictDataManageVOList() {
        DmsDictDataManage dmsDictDataManage = new DmsDictDataManage();
        dmsDictDataManage.setDictType("sms_frequent_used");
        List<DmsDictDataManage> list = dmsDictDataManageService.selectDmsDictDataManageList(dmsDictDataManage);
        //替换集合
        return AjaxResult.success(BeanCopierUtil.copy(list, DmsDictDataManageVO.class));
    }

    /**
     * 查询医生常用诊断（疾病）、检查检验列表
     */
    @PreAuthorize("@ss.hasPermi('dms:used:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询医生常用诊断（疾病）、检查检验(搁置)", notes = "查询医生常用诊断（疾病）、检查检验等",
            code = 200, produces = "application/json", protocols = "Http",
            response = TableDataInfo.class, httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsFrequentUsedVO对象", type = "DmsFrequentUsedVO")
    public TableDataInfo list(DmsFrequentUsedVO dmsFrequentUsedVO) {
        userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //获取常用项类别
        type = dmsFrequentUsedVO.getProjectType();
        startPage();
        //得到登录用户的常用项
        DmsFrequentUsed dmsFrequentUsed = dmsFrequentUsedService.selectDmsFrequentUsedById(userId);
        List list = new ArrayList();
        //根据传入type判断返回常用项列表
        //第一种情况,查询用户下有哪些常用项
        if (type >= DmsConstants.TYPE_WESTERN_MEDICINE ) {
            list = dmsDrugService.selectDmsDrugListByIdsOrTypeOrName(dmsFrequentUsed.getDrugIdList(), type,null);
        } else if (type <= DmsConstants.TYPE_HANDLE) {
            if (type.equals(DmsConstants.TYPE_EXAMINE)) {
                list = dmsNonDrugService.selectDmsNonDrugListByIdsOrTypeOrName(dmsFrequentUsed.getCheckIdList(), type,null);
            } else if (type.equals(DmsConstants.TYPE_INSPECT)) {
                list = dmsNonDrugService.selectDmsNonDrugListByIdsOrTypeOrName(dmsFrequentUsed.getTestIdList(), type,null);
            } else {
                list = dmsNonDrugService.selectDmsNonDrugListByIdsOrTypeOrName(dmsFrequentUsed.getDispositionIdList(), type,null);
            }
        } else {
            list = dmsDiseService.selectDmsDiseListByIdsOrName(dmsFrequentUsed.getMedicineDiseIdList(),null);
        }

        TableDataInfo tableDataInfo = getDataTable(list);
        //替换集合
        if (type.equals(DmsConstants.TYPE_DIAGNOSE)) {
            tableDataInfo.setRows(BeanCopierUtil.copy(tableDataInfo.getRows(), DmsDiseVO.class));
        } else {
            tableDataInfo.setRows(BeanCopierUtil.copy(tableDataInfo.getRows(), DmsFrequentUsedVO.class));
        }

        return tableDataInfo;
    }

    /**
     * 查询所有常用诊断（疾病）、检查检验列表
     */
    @PreAuthorize("@ss.hasPermi('dms:used:allDataList')")
    @GetMapping("/allDataList")
    @ApiOperation(value = "查询所有常用诊断（疾病）、检查检验(搁置)", notes = "查询所有常用诊断（疾病）、检查检验等",
            code = 200, produces = "application/json", protocols = "Http",
            response = TableDataInfo.class, httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsFrequentUsedVO对象", type = "DmsFrequentUsedVO")
    public TableDataInfo allDataList( DmsFrequentUsedVO dmsFrequentUsedVO) {
        //获取常用项类别

        type = dmsFrequentUsedVO.getProjectType();
       String name=dmsFrequentUsedVO.getName();
        startPage();
        //得到登录用户的常用项
        List list = new ArrayList();
        //根据传入type判断返回常用项列表
        //查询所有常用项,或根据名称模糊查询常用项
        if (type >= DmsConstants.TYPE_WESTERN_MEDICINE ) {
            list = dmsDrugService.selectDmsDrugListByIdsOrTypeOrName(null, type,name);
        } else if (type <= DmsConstants.TYPE_HANDLE) {
            if (type.equals(DmsConstants.TYPE_EXAMINE)) {
                list = dmsNonDrugService.selectDmsNonDrugListByIdsOrTypeOrName(null, type,name);
            } else if (type.equals(DmsConstants.TYPE_INSPECT)) {
                list = dmsNonDrugService.selectDmsNonDrugListByIdsOrTypeOrName(null, type,name);
            } else {
                list = dmsNonDrugService.selectDmsNonDrugListByIdsOrTypeOrName(null, type,name);
            }
        } else {
            list = dmsDiseService.selectDmsDiseListByIdsOrName(null,name);
        }

        TableDataInfo tableDataInfo = getDataTable(list);
        //替换集合
        if (type.equals(DmsConstants.TYPE_DIAGNOSE)) {
            tableDataInfo.setRows(BeanCopierUtil.copy(tableDataInfo.getRows(), DmsDiseVO.class));
        } else {
            tableDataInfo.setRows(BeanCopierUtil.copy(tableDataInfo.getRows(), DmsFrequentUsedVO.class));
        }
        return tableDataInfo;
    }

    /**
     * 新增医生常用诊断（疾病）、检查检验(搁置)
     */
    @PreAuthorize("@ss.hasPermi('dms:used:add')")
    @Log(title = "新增医生常用诊断（疾病）、检查检验(搁置)", businessType = BusinessType.INSERT)
    @GetMapping("/add/{id}")
    @ApiOperation(value = "新增医生常用诊断（疾病）、检查检验(搁置)信息", notes = "新增医生常用诊断（疾病）、检查检验(搁置)信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "POST")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "DmsFrequentUsedVO对象", type = "DmsFrequentUsedVO")
    public AjaxResult edit(@PathVariable Integer id) {
        //得到登录用户的常用项
        dmsFrequentUsed = dmsFrequentUsedService.selectDmsFrequentUsedById(userId);
        used.setStaffId(userId);
        boolean whether = true;
        //根据传入type判断添加哪个常用项列表
        if (type >= DmsConstants.TYPE_WESTERN_MEDICINE) {
            used.setDrugIdList(dmsFrequentUsed.getDrugIdList()+","+id);
        } else if (type <= DmsConstants.TYPE_HANDLE) {
            if (type.equals(DmsConstants.TYPE_EXAMINE)) {
                used.setCheckIdList(dmsFrequentUsed.getCheckIdList()+","+id);
            } else if (type.equals(DmsConstants.TYPE_INSPECT)) {
                used.setTestIdList(dmsFrequentUsed.getTestIdList()+","+id);
            } else {
                used.setDispositionIdList(dmsFrequentUsed.getDispositionIdList()+","+id);
            }
        } else {
            used.setMedicineDiseIdList(dmsFrequentUsed.getMedicineDiseIdList()+","+id);
        }
            return toAjax(dmsFrequentUsedService.updateDmsFrequentUsed(used));


    }

    /**
     * 删除医生常用诊断（疾病）、检查检验(搁置)
     */
    @PreAuthorize("@ss.hasPermi('dms:used:remove')")
    @Log(title = "医生常用诊断（疾病）、检查检验(搁置)", businessType = BusinessType.DELETE)
    @GetMapping("/del/{id}")
    @ApiOperation(value = "删除医生常用诊断（疾病）、检查检验(搁置)信息", notes = "删除医生常用诊断（疾病）、检查检验(搁置)信息", code = 200,
            produces = "application/json", protocols = "Http", response = AjaxResult.class,
            httpMethod = "DELETE")
    @ApiResponses({
            @ApiResponse(code = 204, message = "操作已经执行成功，但是没有返回数据"),
            @ApiResponse(code = 303, message = "重定向"),
            @ApiResponse(code = 400, message = "参数列表错误（缺少，格式不匹配）"),
            @ApiResponse(code = 500, message = "系统内部错误"),
            @ApiResponse(code = 404, message = "资源，服务未找到"),
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 401, message = "未授权"),
            @ApiResponse(code = 403, message = "访问受限，授权过期")
    })
    @ApiParam(name = "dmsFrequentUsed.id", type = "Long[]")
    public AjaxResult remove( @PathVariable Integer id) {
        System.out.println(id);
        //得到登录用户的常用项
        DmsFrequentUsed dmsFrequentUsed = dmsFrequentUsedService.selectDmsFrequentUsedById(userId);
        DmsFrequentUsed used = new DmsFrequentUsed();
        used.setStaffId(userId);
        List<Integer> list = new ArrayList<Integer>();
        //根据传入type判断添加哪个常用项列表
        if (type >= DmsConstants.TYPE_WESTERN_MEDICINE) {
            list = transition(dmsFrequentUsed.getDrugIdList());
            list= deleteId(list,id);
            used.setDrugIdList(StringUtils.join(list.toArray(), ","));
        } else if (type <= DmsConstants.TYPE_HANDLE) {
            if (type.equals(DmsConstants.TYPE_EXAMINE)) {
                list = transition(dmsFrequentUsed.getCheckIdList());
                list=deleteId(list,id);
                used.setCheckIdList(StringUtils.join(list.toArray(), ","));
            } else if (type.equals(DmsConstants.TYPE_INSPECT)) {
                list = transition(dmsFrequentUsed.getTestIdList());
                list=deleteId(list,id);
                used.setTestIdList(StringUtils.join(list.toArray(), ","));
            } else {
                list = transition(dmsFrequentUsed.getDispositionIdList());
                list= deleteId(list,id);
                used.setDispositionIdList(StringUtils.join(list.toArray(), ","));
            }
        } else {
            list = transition(dmsFrequentUsed.getMedicineDiseIdList());
            list= deleteId(list,id);
            used.setMedicineDiseIdList(StringUtils.join(list.toArray(), ","));
        }
        return toAjax(dmsFrequentUsedService.updateDmsFrequentUsed(used));
    }


    /**
     * 把常用项id从String转换成List
     *
     * @param ids
     * @return
     */
    private List transition(String ids) {
        List idList = Arrays.asList(ids.split(","));
        ;
        return idList;
    }

    /**
     * 判断新添加的常用项id是否已经存在,不存在则添加
     * @param idList
     * @param id
     * @return
     */
    private boolean existsId(List idList, Integer id) {
        if (idList.contains(id)) {
            return false;
        } else {
            idList.add(id);
        }
        return true;
    }

    /**
     * @param idList id集合
     * @param id     要删除的id
     */
    private List deleteId(List idList, Integer id) {
        List list = new ArrayList(idList);
        for(int i=0;i<list.size();i++){
            Integer temp=Integer.valueOf(list.get(i).toString());
            if(temp.equals(id)){
                list.remove(i);
                break;
            }
        }
        return list;
    }

}
